<?php
define('ROOT_PATH', dirname(dirname(dirname(dirname(__FILE__)))) . '/');
$basename = basename($_SERVER['SCRIPT_FILENAME']);
$basename = explode('.',$basename );
define('CURSCRIPT', reset($basename));
include ROOT_PATH.'inc/class/application.class.php';
application::init();

include_once 'wxpay.class.php';
$wxPay = new WxPay();

$xml = file_get_contents('php://input');
if (!empty($xml)) {
    $data = $wxPay->xmlToArray($xml);
    if ('SUCCESS' == $data['return_code'] // 通信成功
        && 'SUCCESS' == $data['result_code']) // 业务成功
    if ($wxPay->checkSign($data)) { // 检查签名
        $type = 'wechat'; // 公众号支付
        $transaction_id = $data['transaction_id']; // 微信支付订单号
        $out_trade_no = $data['out_trade_no']; // 商户订单号
        $money = intval($data['total_fee']);
        $pay_res = DB::fetch_first("SELECT `uid`, `fee`, `pay`  FROM " . DB::table('paygold_log') . " WHERE   `out_trade_no` = '" . $out_trade_no . "'");
        if (!empty($pay_res)) {
            if ($pay_res['fee'] == $money) { // 检查支付金额
                //关于充值增加金币的操作开始
                $uid = DB::fetch_first("SELECT `uid` FROM " . DB::table('paygold_log') . " WHERE `out_trade_no`='" . $out_trade_no . "'");
                if (empty($uid)) { echo json_encode(array('r' => -1, 'errmsg' => '用户(ID: '.$uid.')不存在')); exit; }
                if (empty($money) || intval($money) < 0) { echo json_encode(array('r' => -1, 'errmsg' => '支付金额必须大于0')); exit; }
                $gold=$money/10;
                $gold= floor($gold);
                DB::query("update ".DB::table('member')." set `gold`=`gold`+".$gold." where uid=".$uid['uid']);
                $date=date('Y-m-d',TIMESTAMP);
                $rec=DB::insert('goldcoin',array('uid'=>$uid['uid'],'type'=>'pay_getgold','goldcoin'=>$gold,'desc'=>'充钱得的金币','date'=>$date,'dateline'=>TIMESTAMP),true);
                if(!$rec>0){
                    echo json_encode(array('r'=>-1));exit;
                }
                //关于充值增加金币的操作结束
                if (0 == $pay_res['pay']) {
                    // 更新订单状态
                    DB::update('paygold_log',
                        array(
                            'order_no' => $transaction_id,
                            'pay' => 1,
                            'paytime' => TIMESTAMP
                        ),
                        array(
                            'out_trade_no' => $out_trade_no
                        )
                    );

                }
                $ret = array(
                    'return_code' => 'SUCCESS',
                    'return_msg' => 'OK'
                );

                echo $wxPay->xml_encode($ret);
                exit;
            }
        }
    }
}

$ret = array(
    'return_code' => 'FAIL',
    'return_msg' => 'ERROR'
);

echo $wxPay->xml_encode($ret);
?>
